/*
 *  Copyright (c) 2012 Shirou Maruyama
 * 
 *   Redistribution and use in source and binary forms, with or without
 *   modification, are permitted provided that the following conditions
 *   are met:
 * 
 *   1. Redistributions of source code must retain the above Copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *   2. Redistributions in binary form must reproduce the above Copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *
 *   3. Neither the name of the authors nor the names of its contributors
 *      may be used to endorse or promote products derived from this
 *      software without specific prior written permission.
 */

#ifndef HUF_WAT_TREE_HPP_
#define HUF_WAT_TREE_HPP_

#include <vector>
#include <string>
#include <iostream>
#include <stdint.h>
#include "BitVec.hpp"

namespace cpi00 {

const uint64_t kMaxAlphabetSize = 256;

#ifndef UINT64_MAX
const uint64_t UINT64_MAX = (18446744073709551615ULL);
#endif

class HufWatTree 
{
public:
  HufWatTree(): NumAlpha_(0), Size_(0), Codes_(), Parent_(), Children_(), 
                Mapping_(0), RMapping_(0), BitVectors_() {}
  void Build(const std::string& str);
  void Build(std::vector<unsigned char>& str);
  uint64_t Access(const uint64_t pos) const;
  uint64_t Rank(const uint64_t code, const uint64_t pos) const;
  uint64_t Size() const;
  void Clear();
  uint64_t Read(std::istream& is);
  uint64_t Write(std::ostream& os) const;

private:
  uint64_t NumAlpha_;
  uint64_t Size_;
  std::vector<uint64_t> Codes_;
  std::vector<uint64_t> Parent_;
  std::vector<uint64_t> Children_;
  std::vector<uint64_t> Mapping_;
  std::vector<uint64_t> RMapping_;
  std::vector<BitVec> BitVectors_;

  void BuildWatTree(const std::vector<unsigned char>& str, 
                 const std::vector<uint64_t>& count);
  void BuildHufTree(const std::vector<uint64_t>& count);
  void InitNode(const uint64_t target, 
                const uint64_t left, const uint64_t right);
  void Insert(const uint64_t code);
  void SetBitVectors(const std::vector<unsigned char>& str);
  void SetCodes();
  bool IsLeaf(const uint64_t node_id) const;

}; // class HufWatTree

} // namespace cpi00

#endif // HUF_WAT_TREE_HPP_
